package com.example.demo.config;


import com.example.demo.model.ReturnResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class ResultConfig implements ResponseBodyAdvice {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // 判断是否要执行下面的 beforeBodyWrite() 方法
        // 需要统一结果返回，就要返回 true
        // 不需要统一结果返回，就返回 false
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 返回前设置返回数据的格式，配合上面的 supports 方法进行统一结果返回
        if(body instanceof ReturnResult<?>){
            return body;
        }
        if(body instanceof String){
            try {
                return objectMapper.writeValueAsString(ReturnResult.success(body));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return ReturnResult.success(body);
    }
}
